<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
    <title>OCR测试页面</title>
</head>
<style type="text/css">
    #app {
        display: flex;
        margin: 50px;
        height: 1000px;
    }

    #app div {
        padding: 50px;
        width: 50%;
        border: solid 1px #000;
        height: 100%;
    }
</style>
<body>
<div id="app">
    <div id="left" class="upload-box clear">
        <input type="file" id="fileInput">
        选择OCR识别使用的语种
        <input type="radio" name="language" value="zh_sim" checked="checked"/> 简体中文
        <input type="radio" name="language" value="eng"/> 英文
        <input id="summit" type="button" value="识别">
        </br>
        <img id="previewImage" src="" alt="Preview Image" width="100%">
    </div>
    <div>
        <h2>识别结果</h2>
        <p>识别时间:<span id="time"></span>毫秒</p>
        <p id="resust"></p>
    </div>
</div>

<script src="https://cdn.staticfile.org/jquery/3.1.0/jquery.min.js"></script>
<script type="text/javascript">
    const fileInput = document.getElementById('fileInput');
    const previewImage = document.getElementById('previewImage');
    fileInput.addEventListener('change', function () {
        const file = fileInput.files[0]; // 获取选中的文件对象
        if (file) {
            let language = $('input[name="language"]:checked').val();
            uploadOcr(file, language);
            const reader = new FileReader();

            reader.addEventListener('load', function () {
                // 当文件读取完成时触发的事件处理函数
                previewImage.src = reader.result;
            });
            reader.readAsDataURL(file);
        }
    });

    document.getElementById('summit').addEventListener('click', function () {
        const file = fileInput.files[0]; // 获取选中的文件对象
        let language = $('input[name="language"]:checked').val();
        uploadOcr(file, language);
    })

    function uploadOcr(file, language) {
        var formData = new FormData();
        formData.append('file', file);

        $.ajax({
            url: "/api/ocr/" + language, // 上传图片的后端接口地址
            type: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            success: function (response) {
                // 上传成功后的处理逻辑
                console.log('上传成功' + response);
                $("#time").html(response.time);
                if (response.success) {
                    $("#resust").html("");
                    for (var i = 0; i < response.texts.length; i++) {
                        $("#resust").append(response.texts[i]).append("<br/>");
                    }
                }
            },
            error: function (xhr, status, error) {
                // 上传失败后的处理逻辑
                console.log('上传失败');
            }
        });
    }
</script>
</body>
</html>
